import { defineComponent, PropType, Ref, ref, computed, onMounted } from 'vue'
import { ElSelect, ElOption } from 'element-plus'
import { getServieList } from '@/api/service'
import ServiceInfo from './ServiceInfo'
import styles from './index.module.scss'

export default defineComponent({
  name: 'SvcSelect',
  props: {
    // 服务id
    modelValue: {
      type: String as PropType<string>,
      default: () => ''
    }
  },
  setup(props, { emit, slots }) {
    const computedModelValue = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val),
    })
    const UrlOption: Ref<JSX.Element | null> = ref() // 下拉选项

    // 获取url选项方法
    const getUrlOptions = async (queryString: string = '') => {
      const query = {
        svcName: queryString,
        onlineSts: 'A',
        current: 1,
        size: 100
      }
      const res = await getServieList({ ...query })
      if (res.status === 200) {
        return res.data.list?.map(item => {
          return {
            label: item.svcName,
            value: item.svcId
          }
        })
      }
      return []
    }

    // 根据关键字筛选url
    const queryUrlAsync = (queryString: string, cb: (arg: any) => void) => {
      
      getUrlOptions(queryString)
        .then(data => {
          cb(data)
        })
    }

    // 初始化下拉选项
    const initOptions = async () => {
      const URL_OPTIONS = await getUrlOptions()
      UrlOption.value = <>
        {URL_OPTIONS.map((item) => {
          return <ElOption {...item} />;
        })}
      </>
    }

    onMounted(() => {
      initOptions()
    })

    return () => <div class={styles['svc-select']}>
      <el-form label-position="left">
        <el-form-item label="选择服务">
          <ElSelect
            class={styles['form-item']}
            v-model={computedModelValue.value}
            filterable={true}
            clearable={true}
            remote={true}
            placeholder="搜索关键词"
            remote-method={queryUrlAsync}
            v-slots={{
              default: (): JSX.Element => UrlOption.value
            }}
          />
        </el-form-item>

        <ServiceInfo
          v-model={computedModelValue.value}
        />
      </el-form>
    </div>
  }
})